
/**
This file is part of Gel2DE.

    Gel2DE is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Gel2DE is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Gel2DE.  If not, see <http://www.gnu.org/licenses/>.

	Copyright (C) 2012, University of Bergen
*/

// -*- C++ -*- generated by wxGlade 0.6.3 on Fri Jul 04 14:56:41 2008

#include "GelCorrelationGUI.h"

// begin wxGlade: ::extracode
// end wxGlade



GelImageAnalysisFrame::GelImageAnalysisFrame(wxWindow* parent, int id, const wxString& title, const wxPoint& pos, const wxSize& size, long style):
    wxFrame(parent, id, title, pos, size, wxDEFAULT_FRAME_STYLE)
{
    // begin wxGlade: GelImageAnalysisFrame::GelImageAnalysisFrame
    panel_1 = new wxPanel(this, wxID_ANY);
    frame_1_menubar = new wxMenuBar();
    wxMenu* File = new wxMenu();
    File->Append(2, wxT("Open project..."), wxEmptyString, wxITEM_NORMAL);
    File->Append(3, wxT("Save registration..."), wxEmptyString, wxITEM_NORMAL);
    File->Append(4, wxT("Save project"), wxEmptyString, wxITEM_NORMAL);
    File->AppendSeparator();
    File->Append(5, wxT("Result screen dump"), wxEmptyString, wxITEM_NORMAL);
	File->Append(6, wxT("Export ROI"), wxEmptyString, wxITEM_NORMAL);
	File->Append(7, wxT("Specify ROI"), wxEmptyString, wxITEM_NORMAL);
    File->AppendSeparator();
	File->Append(8, wxT("Close project"), wxEmptyString, wxITEM_NORMAL);
	File->AppendSeparator();
    File->Append(9, wxT("Exit"), wxEmptyString, wxITEM_NORMAL);
    frame_1_menubar->Append(File, wxT("File"));
    SetMenuBar(frame_1_menubar);
    wx_calcCorr = new wxButton(panel_1, 101, wxT("Calculate corr"));
	wx_calcPermTest = new wxButton(panel_1, 102, wxT("Permutation test"));

	const wxString wx_imgselector_choices[] = {
        wxT("Data"),
        wxT("Standard")
    };
    wx_imgselector = new wxRadioBox(panel_1, 301, wxT("Image type"), wxDefaultPosition, wxDefaultSize, 2, wx_imgselector_choices, 0, wxRA_SPECIFY_ROWS);

	const wxString wx_zoomNavigateRadio_choices[] = {
        wxT("Register"),
        wxT("Navigate"),
		wxT("ROI select")
    };
    wx_zoomNavigateRadio = new wxRadioBox(panel_1, 302, wxT("Mode"), wxDefaultPosition, wxDefaultSize, 3, wx_zoomNavigateRadio_choices, 0, wxRA_SPECIFY_ROWS);

	const wxString wx_normalizationRadio_choices[] = {
		wxT("None"),
		wxT("Mean"),
		wxT("Median"),
		wxT("z-score")
	};
	wx_normalizationRadio = new wxRadioBox(panel_1, 303, wxT("Normalization"), wxDefaultPosition, wxDefaultSize, 4, wx_normalizationRadio_choices, 0, wxRA_SPECIFY_ROWS);

    wx_FixedIntensitySlider = new wxSlider(panel_1, 202, 0, 0, 100, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS);
	wx_imgWindowSlider = new wxSlider(panel_1, 204, 0, 0, 64000, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS); 
	wx_imgCenterSlider = new wxSlider(panel_1, 205, 0, 0, 64000, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS); 
	wx_blurSlider = new wxSlider(panel_1, 206, 0, 0, 100, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS);

	const wxString wx_resultMode_choices[] = {
        wxT("Raw correlation (C)"),
        wxT("Sign wght (C*S)"),
        wxT("StdDev wght (C*S*D)"),
        wxT("Sign (S)"),
        wxT("StdDev (D)"),
		wxT("p-value (t-dist)"),
		wxT("p-value (perm)")
    };
    wx_resultMode = new wxChoice(panel_1, 501, wxDefaultPosition, wxDefaultSize, 7, wx_resultMode_choices, 0);
    ctfSlider = new wxSlider(panel_1, 203, 0, 1, 100, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS);
    wx_gridFileList = new wxGrid(panel_1, 401);

    set_properties();
	initVTKDisplays(panel_1);
    do_layout();
    // end wxGlade
}


BEGIN_EVENT_TABLE(GelImageAnalysisFrame, wxFrame)
    // begin wxGlade: GelImageAnalysisFrame::event_table
    EVT_MENU(2, GelImageAnalysisFrame::OpenProject)
    EVT_MENU(3, GelImageAnalysisFrame::SaveRegistration)
    EVT_MENU(4, GelImageAnalysisFrame::SaveProject)
    EVT_MENU(5, GelImageAnalysisFrame::ResultScreenDump)
	EVT_MENU(6, GelImageAnalysisFrame::ExportData)
	EVT_MENU(7, GelImageAnalysisFrame::ShowTextEntryDialog)
	EVT_MENU(8, GelImageAnalysisFrame::CloseProject)
    EVT_MENU(9, GelImageAnalysisFrame::ExitApplication)
    EVT_BUTTON(101, GelImageAnalysisFrame::CalcCorrClicked)
	EVT_BUTTON(102, GelImageAnalysisFrame::CalcPermutationClicked)
    EVT_RADIOBOX(301, GelImageAnalysisFrame::ImageTypeChanged)
    EVT_RADIOBOX(302, GelImageAnalysisFrame::NavigationModeChanged)
	EVT_RADIOBOX(303, GelImageAnalysisFrame::NormalizationModeChanged)
    EVT_COMMAND_SCROLL(202, GelImageAnalysisFrame::IntensityFixedChanged)
    EVT_CHOICE(501, GelImageAnalysisFrame::ResultModeChanged)
    EVT_COMMAND_SCROLL(203, GelImageAnalysisFrame::ctfScalerScrolled)
    EVT_GRID_CMD_CELL_LEFT_DCLICK(401, GelImageAnalysisFrame::CellSelected)
	EVT_COMMAND_SCROLL(204, GelImageAnalysisFrame::ImgWindowChanged)
	EVT_COMMAND_SCROLL(205, GelImageAnalysisFrame::ImgCenterChanged)
	EVT_COMMAND_SCROLL(206, GelImageAnalysisFrame::BlurChanged)
    // end wxGlade
END_EVENT_TABLE();

void GelImageAnalysisFrame::SaveRegistration(wxCommandEvent &event)
{
	m_gelCorrelationAnalysis->ToXML(m_projectConfiguration->getRegistrationFile()->path().c_str());
}

void GelImageAnalysisFrame::CloseProject(wxCommandEvent &event)
{
	m_projectConfiguration->Clear();
	m_gelCorrelationAnalysis->Clear();
	m_gelImageViewer->Clear();
	m_resultImageViewer->Clear();
	m_gelImageViewer->Render();
	EmptyGelTable();

}

void GelImageAnalysisFrame::ImgWindowChanged(wxScrollEvent &event)
{
	double window = event.GetPosition();
	m_gelImageViewer->SetWindow(window);
	m_gelImageViewer->Render();
}

void GelImageAnalysisFrame::ImgCenterChanged(wxScrollEvent &event)
{
	double level = event.GetPosition();
	m_gelImageViewer->SetLevel(level);
	m_gelImageViewer->Render();
}

void GelImageAnalysisFrame::BlurChanged(wxScrollEvent &event)
{
	double sigma = event.GetPosition()/10.;
	m_gelCorrelationAnalysis->SetBlurLevel(sigma);
	m_gelImageViewer->Render();

}

void GelImageAnalysisFrame::ShowTextEntryDialog(wxCommandEvent &event)
{
    wxTextEntryDialog dialog(this,
                             _T("Please enter the ROI on the format x,y;x,y where the two pairs are the start and stop coordinate:"),
                             _T("Specify ROI"),
							 _T("")
                             _T(""),
                             wxOK | wxCANCEL);

	dialog.ShowModal();

	wxString input = dialog.GetValue();
	int pos = input.find(";");
	wxString firstPair = input.substr(0, pos);
	wxString seconPair = input.substr(pos + 1, input.size());
	pos = firstPair.find(",");
	wxString firstX = firstPair.substr(0, pos);
	wxString firstY = firstPair.substr(pos + 1, firstPair.size());
	pos = seconPair.find(",");
	wxString seconX = seconPair.substr(0, pos);
	wxString seconY = seconPair.substr(pos + 1, seconPair.size());

/* for debug.
	wxMessageBox(firstX, _T(""), wxOK | wxICON_INFORMATION, this);
	wxMessageBox(firstY, _T(""), wxOK | wxICON_INFORMATION, this);
	wxMessageBox(seconX, _T(""), wxOK | wxICON_INFORMATION, this);
	wxMessageBox(seconY, _T(""), wxOK | wxICON_INFORMATION, this);
*/
	int x1;
	int y1;
	int x2;
	int y2;

	std::istringstream s_x1((std::string)firstX);
	s_x1 >> x1;
	std::istringstream s_y1((std::string)firstY);
	s_y1 >> y1;
	std::istringstream s_x2((std::string)seconX);
	s_x2 >> x2;
	std::istringstream s_y2((std::string)seconY);
	s_y2 >> y2;

	m_resultImageViewer->SetRoi(x1, y1, 0, x2, y2, 0);

}

void GelImageAnalysisFrame::ExportData(wxCommandEvent &event)
{
	//Do something about exporting data.
	wxString newFileName = wxFileSelector("Choose a file to export to", 0, 0, NULL, "txt files (*.txt) | *.txt");
	if(newFileName == "") return;

	//GelCorrelationAnalysis::DataImageType::RegionType roi;
	GelCorrelationAnalysis::RGBImageType::RegionType roi;
	m_gelImageViewer->GetROIDefinition(&roi);
	m_gelCorrelationAnalysis->ExportData(roi, std::string(newFileName.c_str()));
	
}

void GelImageAnalysisFrame::SaveProject(wxCommandEvent &event)
{
	putGUIStateOnGelImages();
	m_gelCorrelationAnalysis->ToXML(m_projectConfiguration->getRegistrationFile()->path().c_str());
	std::vector<GelImage*>::iterator i = m_gelCorrelationAnalysis->GetGelImages()->begin();
	std::vector<std::string*>* excludedGelImages = new std::vector<std::string*>();
	for(i; i != m_gelCorrelationAnalysis->GetGelImages()->end(); ++i)
	{
		if(!(*i)->isEnabled())
		{
			excludedGelImages->push_back(new std::string((*i)->GetFileName()));
		}
	}
	m_projectConfiguration->ToXML(m_projectConfiguration->getProjectFile(), excludedGelImages);
}


void GelImageAnalysisFrame::OpenProject(wxCommandEvent &event)
{

	wxString newFileName = wxFileSelector("Choose a file to open", 0, 0, NULL, "XML files (*.xml) | *.xml");
	if(newFileName == "") return;

//	m_gelCorrelationAnalysis->Clear();

	m_projectConfiguration->FromXML(std::string(newFileName.c_str()));
	m_fileLog->DisplayText("Loaded project file:");
	m_fileLog->DisplayText(newFileName.c_str());

	if(m_projectConfiguration->getCtfFile()) m_ctfMgr->LoadCTF(m_projectConfiguration->getCtfFile()->path());
	m_fileLog->DisplayText("Loaded CTF");

	m_ctfMgr->setCurrentCtf(0);

	vtkColorTransferFunction *newCtf = vtkColorTransferFunction::New();
	vtkColorTransferFunction* masterFunc = m_ctfMgr->getCurrentTransferFunction();

	double val[6];

	for(int i = 0; i < masterFunc->GetSize(); i++)
	{
		masterFunc->GetNodeValue(i, val);
		newCtf->AddRGBPoint(val[0], val[1], val[2], val[3]);
	}

	newCtf->Build();

	m_gelCorrelationAnalysis = new GelCorrelationAnalysis(m_fileLog);
	m_gelImageViewer->SetGelCorrelationAnalysis(m_gelCorrelationAnalysis);
	m_resultImageViewer->SetGelCorrelationAnalysis(m_gelCorrelationAnalysis);

	m_gelCorrelationAnalysis->SetColorTransferFunction(newCtf);//m_ctfMgr.getCurrentTransferFunction());
	m_resultImageViewer->SetColorTransferFunction(newCtf);//m_ctfMgr.getCurrentTransferFunction());

	m_gelCorrelationAnalysis->LoadConfiguration(m_projectConfiguration);
	populateGelTable();
	putGelImagesStateOnGUI();
	m_gelImageViewer->SelectMovingImage(0);
	m_gelImageViewer->SelectFixedImage(0);
	m_gelImageViewer->ResetCamera();
}


void GelImageAnalysisFrame::ExitApplication(wxCommandEvent &event)
{
	Close(true);
}
void GelImageAnalysisFrame::NavigationModeChanged(wxCommandEvent &event)
{
	int sel = event.GetSelection();
	if(sel == 0)
	{
		m_gelImageViewer->RegisterMode();
	}
	else if(sel == 1)
	{
		m_gelImageViewer->ZoomMode();
	}
	else if(sel == 2)
	{
		m_gelImageViewer->ROIMode();
	}
}

void GelImageAnalysisFrame::NormalizationModeChanged(wxCommandEvent &event)
{
	int sel = event.GetSelection();
	m_gelCorrelationAnalysis->SetNormalizationMode(sel);
	m_gelImageViewer->Render();
}

void GelImageAnalysisFrame::ResultModeChanged(wxCommandEvent &event)
{
	int element = event.GetSelection();
	m_resultImageViewer->DisplayElement(element);
	m_resultImageViewer->Update();
}

void GelImageAnalysisFrame::putGelImagesStateOnGUI()
{
	//Better to have a table model, see wxGelImageTable.
	std::vector<GelImage*>* images = m_gelCorrelationAnalysis->GetGelImages();
	std::vector<GelImage*>::iterator i = images->begin();
	int counter = 0;
	for(i; i != images->end(); ++i)
	{
		if((*i)->isEnabled())
		{
			wx_gridFileList->SetCellValue(wxString("1"), counter, 0);
		}
		else
		{
			wx_gridFileList->SetCellValue(wxString(""), counter, 0);
		}
		counter++;
	}

}


void GelImageAnalysisFrame::putGUIStateOnGelImages()
{
	//Better to have a table model, see wxGelImageTable.
	std::vector<GelImage*>* images = m_gelCorrelationAnalysis->GetGelImages();
	std::vector<GelImage*>::iterator i = images->begin();
	int counter = 0;
	for(i; i != images->end(); ++i)
	{
		wxString enabled = wx_gridFileList->GetCellValue(counter, 0);
		if(enabled == "1")
		{
			(*i)->SetEnabled(true);
		}
		else
		{
			(*i)->SetEnabled(false);
		}
		counter++;
	}

}

void GelImageAnalysisFrame::CalcPermutationClicked(wxCommandEvent &event)
{
	wxArrayInt a = wx_gridFileList->GetSelectedCols();
	if(a.GetCount() == 0)
	{
		wxMessageBox(_T("Please select a parameter for the correlation analysis."), 
			      _T("Error"), wxOK | wxICON_INFORMATION, this); 
		return; 
	}
	std::set<const std::string> selectedParameters;
	for(int i = 0; i < a.GetCount(); i++)
	{
		const std::string parName(wx_gridFileList->GetColLabelValue(a[i]).c_str());
		selectedParameters.insert(parName);
	}
	

	//It is the m_gelCorrelationAnalysis that needs to do it. So:
	GelCorrelationAnalysis::DataImageType::RegionType roi;
	m_resultImageViewer->GetROIDefinition(&roi);
	
	m_gelCorrelationAnalysis->RunPermutationTest(roi, selectedParameters, true);
	m_resultImageViewer->Load();
	int element = wx_resultMode->GetSelection();
	m_resultImageViewer->UpdateConnectors();
	m_resultImageViewer->DisplayElement(element);
	m_resultImageViewer->Update();
	

	//m_resultImageViewer->G
	//m_gelCorrelationAnalysis->doPermutationTest(region, npermutations);
	//This should produce an image that could be seen in the resultimage viewer.

}

void GelImageAnalysisFrame::CalcCorrClicked(wxCommandEvent &event)
{
	//We need to decide for which parameters we want to 
	//run the analysis.
	wxArrayInt a = wx_gridFileList->GetSelectedCols();
	if(a.GetCount() == 0)
	{
		wxMessageBox(_T("Please select a parameter for the correlation analysis."), 
			      _T("Error"), wxOK | wxICON_INFORMATION, this); 
		return; 
	}
	std::set<const std::string> selectedParameters;
	for(int i = 0; i < a.GetCount(); i++)
	{
		const std::string parName(wx_gridFileList->GetColLabelValue(a[i]).c_str());
		selectedParameters.insert(parName);
	}

	putGUIStateOnGelImages();

	::wxBeginBusyCursor();

	m_gelCorrelationAnalysis->RunAnalysis(selectedParameters);

	gel2de::File* outDir = m_gelCorrelationAnalysis->GetPreviousAnalysisOutputDir();

	//Write registration:
	m_gelCorrelationAnalysis->ToXML(
		gel2de::File((*outDir), "registration.xml").path().c_str());

	//Write project:
	std::vector<std::string*>* excludedGelImages = new std::vector<std::string*>();
	std::vector<GelImage*>::iterator i = m_gelCorrelationAnalysis->GetGelImages()->begin();
	for(i; i != m_gelCorrelationAnalysis->GetGelImages()->end(); ++i)
	{
		if(!(*i)->isEnabled())
		{
			excludedGelImages->push_back(new std::string((*i)->GetFileName()));
		}
	}
	m_projectConfiguration->ToXML(
		(*outDir).path() + "/project.xml", excludedGelImages);

	//Write parametersfile:
	
	gel2de::File outFile((*outDir), "parameters.xml");

	ifstream source(m_projectConfiguration->getParameterFile()->path().c_str(), fstream::binary);
	ofstream dest(outFile.path().c_str(), fstream::trunc|fstream::binary);
	dest << source.rdbuf();



	//Load new images into resultimageviewer.

	m_resultImageViewer->Load(outDir, m_gelCorrelationAnalysis->GetPreviousIdString());
	std::string name = (*(selectedParameters.begin()));
	int numberOfGels = m_gelCorrelationAnalysis->GetNumberOfActiveGels((*(selectedParameters.begin())));
	double average = m_gelCorrelationAnalysis->GetAverage((*selectedParameters.begin()));
	m_resultImageViewer->SetMetaInfo(name, numberOfGels, average);

	::wxEndBusyCursor();

	//Update GUI state. This could also be done by the correlationanalysis which changed it in the first place.
	SetImageType(wx_imgselector->GetSelection());
	int element = wx_resultMode->GetSelection();
	m_resultImageViewer->UpdateConnectors();
	m_resultImageViewer->DisplayElement(element);
	m_resultImageViewer->Update();

}

void GelImageAnalysisFrame::CellSelected(wxGridEvent &event)
{
	int row = event.GetRow();
	if(this->IsShown()) m_gelImageViewer->SelectMovingImage(row);
	m_gelImageViewer->Render();
}

// wxGlade: add GelImageAnalysisFrame event handlers
void GelImageAnalysisFrame::IntensityFixedChanged(wxScrollEvent &event)
{
	int pos = event.GetPosition();
	double angle = ((double)pos/100.)*(3.14/2);
	
	double cosAngle = cos(angle);
	double sinAngle = sin(angle);

	double movingOpacity = cosAngle;
	double fixedOpacity = sinAngle;

	//m_gelImageViewer->SetFixedOpacity((double)pos/100.);
	//m_gelImageViewer->SetMovingOpacity((double)(100. - pos)/100.);
	m_gelImageViewer->SetFixedOpacity(fixedOpacity);
	m_gelImageViewer->SetMovingOpacity(movingOpacity);

}

void GelImageAnalysisFrame::ImageTypeChanged(wxCommandEvent &event)
{
	int sel = event.GetSelection();
	SetImageType(sel);
	m_gelImageViewer->Render();
}

void GelImageAnalysisFrame::SetImageType(int aType)
{
	if(aType == 0)
	{
		m_gelImageViewer->ShowData();
	}
	else
	{
		m_gelImageViewer->ShowStandard();
	}
}

void GelImageAnalysisFrame::ResultScreenDump(wxCommandEvent &event)
{
	m_resultImageViewer->ScreenDump();
}

void GelImageAnalysisFrame::ctfScalerScrolled(wxScrollEvent &event)
{

	int pos = event.GetPosition();
	double relPos = pow(0.9, (double)pos/5.);

	vtkColorTransferFunction *newCtf = vtkColorTransferFunction::New();
	vtkColorTransferFunction* masterFunc = m_ctfMgr->getCurrentTransferFunction();

	//Leak of ctf, fix it if concept is nice.

	double val[6];
	masterFunc->GetNodeValue(0, val);
	newCtf->AddRGBPoint(val[0], val[1], val[2], val[3]);
	masterFunc->GetNodeValue(masterFunc->GetSize() - 1, val);
	newCtf->AddRGBPoint(val[0], val[1], val[2], val[3]);
	
	for(int i = 0; i < masterFunc->GetSize(); i++)
	{
		masterFunc->GetNodeValue(i, val);
		newCtf->AddRGBPoint(val[0]*relPos, val[1], val[2], val[3]);
	}

	newCtf->Build();
	m_resultImageViewer->SetColorTransferFunction(newCtf);
	m_gelCorrelationAnalysis->SetColorTransferFunction(newCtf);

	m_resultImageViewer->Render();

}

void GelImageAnalysisFrame::set_properties()
{
    // begin wxGlade: GelImageAnalysisFrame::set_properties
    SetTitle(wxT("Gel2DE v1.0.0"));
    wx_calcCorr->SetToolTip(wxT("Click to calculate correlation"));
	wx_calcPermTest->SetToolTip(wxT("Click to perform permutation test"));
    wx_imgselector->SetSelection(0);
    wx_zoomNavigateRadio->SetSelection(1);
	wx_normalizationRadio->SetSelection(0);
    wx_resultMode->SetSelection(0);
    ctfSlider->SetToolTip(wxT("Scale color table"));
    wx_gridFileList->CreateGrid(0, 2);
    wx_gridFileList->SetColLabelValue(0, wxT("Kol1"));

	wx_FixedIntensitySlider->SetToolTip(wxT("Fade to reference image"));
	wx_imgWindowSlider->SetToolTip(wxT("Adjust window (contrast)"));
	wx_imgCenterSlider->SetToolTip(wxT("Adjust level (brightness)"));
	wx_blurSlider->SetToolTip(wxT("Adjust blur radius"));

    // end wxGlade
}


void GelImageAnalysisFrame::do_layout()
{
    // begin wxGlade: GelImageAnalysisFrame::do_layout
    wxBoxSizer* sizer_1 = new wxBoxSizer(wxVERTICAL);
    wxFlexGridSizer* wx_ViewConsoleSizer = new wxFlexGridSizer(2, 1, 0, 0);
    wxFlexGridSizer* grid_sizer_3 = new wxFlexGridSizer(2, 1, 0, 0);
    wxFlexGridSizer* wx_ViewSizer = new wxFlexGridSizer(1, 4, 0, 0);
    wxFlexGridSizer* wx_GelImageSizer = new wxFlexGridSizer(2, 2, 0, 0);
    wxFlexGridSizer* grid_sizer_4 = new wxFlexGridSizer(2, 1, 0, 0);
    wxGridSizer* grid_sizer_1 = new wxGridSizer(1, 4, 0, 0);
    wxFlexGridSizer* grid_sizer_2 = new wxFlexGridSizer(5, 1, 0, 0);
    grid_sizer_2->Add(wx_calcCorr, 1, wxEXPAND, 0);
	grid_sizer_2->Add(wx_calcPermTest, 1, wxEXPAND, 0);
    grid_sizer_2->Add(wx_imgselector, 1, wxEXPAND, 0);
    grid_sizer_2->Add(wx_zoomNavigateRadio, 1, wxEXPAND, 0);
	grid_sizer_2->Add(wx_normalizationRadio, 1, wxEXPAND, 0);
    wx_ViewSizer->Add(grid_sizer_2, 1, wxEXPAND, 0);
    grid_sizer_1->Add(wx_FixedIntensitySlider, 0, 0, 0);
	grid_sizer_1->Add(wx_imgCenterSlider, 0, 0, 0);
	grid_sizer_1->Add(wx_imgWindowSlider, 0, 0, 0);
	grid_sizer_1->Add(wx_blurSlider, 0, 0, 0);
	layoutVTKDisplays(wx_GelImageSizer);
    wx_GelImageSizer->Add(grid_sizer_1, 1, wxEXPAND, 0);
    grid_sizer_4->Add(wx_resultMode, 0, 0, 0);
    grid_sizer_4->Add(ctfSlider, 0, 0, 0);
    wx_GelImageSizer->Add(grid_sizer_4, 1, wxEXPAND, 0);
    wx_GelImageSizer->AddGrowableRow(0);
    wx_GelImageSizer->AddGrowableCol(0);
    wx_GelImageSizer->AddGrowableCol(1);
    wx_ViewSizer->Add(wx_GelImageSizer, 1, wxEXPAND, 0);
    wx_ViewSizer->AddGrowableRow(0);
    wx_ViewSizer->AddGrowableCol(1);
    wx_ViewSizer->AddGrowableCol(2);
	wx_ViewConsoleSizer->AddGrowableRow(0);
	wx_ViewConsoleSizer->AddGrowableCol(0);
    wx_ViewConsoleSizer->Add(wx_ViewSizer, 1, wxEXPAND, 0);
    grid_sizer_3->Add(wx_gridFileList, 1, wxEXPAND, 0);
    wx_ViewConsoleSizer->Add(grid_sizer_3, 1, wxEXPAND, 0);
    panel_1->SetSizer(wx_ViewConsoleSizer);
    sizer_1->Add(panel_1, 1, wxEXPAND, 0);
    SetSizer(sizer_1);
    sizer_1->Fit(this);
    Layout();
    // end wxGlade
}

void GelImageAnalysisFrame::layoutVTKDisplays(wxFlexGridSizer* aImageSizer)
{
	/*
	wx_ViewConsoleSizer->AddGrowableRow(0, 1);
	wx_ViewConsoleSizer->AddGrowableCol(0, 1);

	wx_ViewSizer->AddGrowableCol(1, 1);
	wx_ViewSizer->AddGrowableCol(2, 1);
	wx_ViewSizer->AddGrowableRow(0, 1);

	wx_GelImageSizer->AddGrowableRow(0, 1);
	wx_GelImageSizer->AddGrowableCol(0, 1);

	wx_ResultSizer->AddGrowableRow(0, 1);
	wx_ResultSizer->AddGrowableCol(0, 1);
	*/

	aImageSizer->Add(m_imageDisplay, 1, wxEXPAND | wxALL /*wxEXPAND | wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL*/ , 5);
	aImageSizer->Add(m_resultDisplay, 1, wxEXPAND | wxALL /*wxEXPAND | wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL*/ , 5);
}
void GelImageAnalysisFrame::initVTKDisplays(wxPanel* aPanel)
{
	m_fileLog = vtkFileOutputWindow::New();
	m_fileLog->SetFileName("gel2de.log");
	m_fileLog->SetInstance(m_fileLog);

	m_fileLog->DisplayText("Initializing gel2de...");

	m_ctfMgr = new TransferFunctionManager(m_fileLog);

	//m_gelCorrelationAnalysis = new GelCorrelationAnalysis(m_fileLog);
	m_gelCorrelationAnalysis = NULL;
	m_projectConfiguration = new ProjectConfiguration();
	
	wx_gridFileList->SetMinSize(wxSize(800, 300));

	populateGelTable();

	m_imageDisplay = new wxVTKRenderWindowInteractor(aPanel, wxID_ANY);
	((wxWindow*)m_imageDisplay)->SetMinSize(wxSize(500, 500));
	m_gelImageViewer = new GelImageViewer(m_imageDisplay);//, m_gelCorrelationAnalysis);

	m_resultDisplay = new wxVTKRenderWindowInteractor(aPanel, wxID_ANY);
	((wxWindow*)m_resultDisplay)->SetMinSize(wxSize(500, 500));
	//Bad: these two should not need to know of each other...
	m_resultImageViewer = new ResultImageViewer(m_resultDisplay, "", m_gelImageViewer, m_ctfMgr->getTransferFunction(0));

	m_gelImageViewer->SetResultImageViewer(m_resultImageViewer);
	m_gelImageViewer->ZoomMode();
}

void GelImageAnalysisFrame::EmptyGelTable()
{
	//Empty current table.
	if(wx_gridFileList->GetNumberRows() != 0)
	{
		wx_gridFileList->DeleteRows(0, wx_gridFileList->GetNumberRows());
	}

	while(wx_gridFileList->GetNumberCols() > 2)
	{
		wx_gridFileList->DeleteCols(wx_gridFileList->GetNumberCols() - 1);
	}
}

void GelImageAnalysisFrame::populateGelTable()
{
	//Empty current table.
	EmptyGelTable();

	std::vector<GelImage*>* files;// = m_gelCorrelationAnalysis->GetGelImages();
	std::set<const std::string> parameterNames;// = m_gelCorrelationAnalysis->getAllParameterTypes();

	if (m_gelCorrelationAnalysis)
	{
		files = m_gelCorrelationAnalysis->GetGelImages();
		parameterNames = m_gelCorrelationAnalysis->getAllParameterTypes();
	}
	else
	{
		files = new std::vector<GelImage*>();
		//parameterNames = new std::set<const std::string>();
	}

	wx_gridFileList->AppendCols(parameterNames.size());

	wxGridCellAttr *readOnlyAttr = new wxGridCellAttr();

	readOnlyAttr->SetReadOnly(TRUE);

	wx_gridFileList->SetColFormatBool(0);

	wx_gridFileList->SetColLabelValue(0, wxT("Enabled"));
	wx_gridFileList->SetColLabelValue(1, wxT("File name"));

	wx_gridFileList->SetColAttr(1, readOnlyAttr);


	std::set<const std::string>::iterator inames = parameterNames.begin();
	int colCounter = 2;
	for(inames; inames != parameterNames.end(); ++inames)
	{
		wx_gridFileList->SetColLabelValue(colCounter, wxT((*inames)));
		wx_gridFileList->SetColFormatFloat(colCounter);
		wx_gridFileList->SetColAttr(colCounter, readOnlyAttr);
		colCounter++;
	}

	std::vector<GelImage*>::iterator gelImageIter = files->begin();
	int rowCount = 0;
	for(gelImageIter; gelImageIter != files->end(); gelImageIter++)
	{
		wx_gridFileList->SetCellEditor(rowCount, 0, new wxGridCellBoolEditor());

		wx_gridFileList->AppendRows();
		wx_gridFileList->SetCellValue(rowCount, 0, wxT("1"));
		wx_gridFileList->SetCellValue(rowCount, 1, (*gelImageIter)->GetFileName());
		char str[20];

		int colCount = 2;
		for(inames = parameterNames.begin(); inames != parameterNames.end(); ++inames)
		{
			if((*gelImageIter)->HasParameterValue(*inames))
			{
				sprintf_s(str, "%f", (*gelImageIter)->GetParameterValue(*inames));
				wx_gridFileList->SetCellValue(rowCount, colCount, wxT(str));
			}
			colCount++;
		}
		rowCount++;
	}

	wx_gridFileList->AutoSize();


}


//Comment out everything below here to get rid of the GUI.


class GelCorrelationApp: public wxApp {
public:
	bool OnInit();
};

IMPLEMENT_APP(GelCorrelationApp)

bool GelCorrelationApp::OnInit()
{
	wxInitAllImageHandlers();
  wxPoint pos(0,0);
  wxSize size(500,500);
	wxFrame * frame_1 = new GelImageAnalysisFrame(NULL, wxID_ANY, wxEmptyString, pos, size);
	SetTopWindow(frame_1);
	frame_1->Show();
	return true;
}































































